<!-- pages/chat/chat.vue -->
<template>
	<view class="chat-container work-container">
		<!-- 聊天消息区域 -->
		<scroll-view class="chat-list" scroll-y="true" :scroll-into-view="lastMsgId" :scroll-with-animation="true"
			:style="{ paddingBottom: inputAreaHeight + 'px' }">
			<view v-for="(item, index) in messages" :key="item.id" :id="'msg'+index" class="message-item" :class="{
          'user-message': item.isUser,
          'bot-message': !item.isUser,
          'typing-status': item.isLoading
        }">
				<!-- 用户消息 -->
				<view v-if="item.isUser" class="message-bubble">
					<text class="message-content">{{ item.content }}</text>
					<text class="message-time">{{ item.time }}</text>
				</view>

				<!-- 机器人消息 -->
				<view v-else-if="!item.isLoading" class="message-bubble">
					<mp-html :content="processContent(item.content)" :tag-style="tagStyles" :selectable="true"
						@linktap="handleLinkClick" />
					<!-- <text class="message-content">{{ item.content }}</text> -->
					<text class="message-time">{{ item.time }}</text>
				</view>

				<!-- 加载状态 -->
				<view v-else class="typing-bubble">
					<view class="typing-indicator">
						<view class="dot"></view>
						<view class="dot"></view>
						<view class="dot"></view>
					</view>
					<text class="typing-text">思考中...</text>
				</view>
			</view>
		</scroll-view>

		<!-- 固定底部输入区域 -->
		<view class="input-area fixed-input" :style="{ bottom: bottomMenuHeight + 'px' }">
			<!-- 新增附件按钮 -->
			<view class="add-btn" @click="toggleFilePanel">
				<uni-icons type="plus" size="28" color="#666"></uni-icons>
			</view>

			<!-- 文件选择面板 -->
			<view v-if="showFilePanel" class="file-panel">
				<view class="file-item" @click="chooseFile">
					<uni-icons type="folder" size="36" color="#07c160"></uni-icons>
					<text class="file-text">选择文件</text>
					<text v-if="uploading">上传进度: {{progress}}%</text>
					<text v-if="error">{{error}}</text>
				</view>
			</view>
			<uni-easyinput class="input-box" v-model="inputMessage" placeholder="请输入消息..." :styles="inputStyles"
				@confirm="sendMessage" :focus="autoFocus" />
			<button class="send-btn" type="primary" @click="sendMessage"
				:disabled="isSending">{{ isSending ? '发送中...' : '发送' }}</button>
		</view>
	</view>
</template>

<script>
	import {
		getChatInfo,
		uploadFile,
		getInitChatInfo
	} from '@/api/chat/chat'
	import mpHtml from '@/components/mp-html/mp-html'
	import xss from 'xss'
	let messageId = 0

	export default {
		data() {
			return {
				// 附件信息
				showFilePanel: false,
				attachments: [],
				uploading: false,
				progress: 0,
				error: '',
				filePath: '',

				messages: [],
				inputMessage: '',
				isSending: false,
				lastMsgId: '',
				autoFocus: true,
				bottomMenuHeight: 50, // 初始底部菜单高度
				inputAreaHeight: 100, // 输入区域预估高度
				inputStyles: {
					backgroundColor: '#fff',
					borderColor: '#eee'
				},
				safeAreaBottom: 0,
				// HTML标签样式配置
				tagStyles: {
					code: 'padding: 2px 4px; background: #f5f5f5; border-radius: 3px; font-family: Consolas;',
					pre: 'padding: 10px; background: #f8f8f8; border-radius: 5px; overflow-x: auto;',
					a: 'color: #007AFF; text-decoration: underline;',
					img: 'max-width: 100%; height: auto; border-radius: 4px; margin: 8px 0;',
					table: 'width: 100%; border-collapse: collapse; margin: 10px 0;',
					th: 'background: #f8f8f8; padding: 8px; border: 1px solid #ddd;',
					td: 'padding: 8px; border: 1px solid #ddd;'
				},

				// 输入框样式
				inputStyles: {
					borderColor: '#eee',
					borderRadius: '20px',
					padding: '12px 16px'
				}
			}
		},
		mounted() {
			this.calculateLayout()
		},
		onLoad() {
			this.init_message();
		},
		methods: {
			//初始化消息
			async init_message() {
				//获取对话记录
				//获取登录后对话
				// 添加加载状态消息
				const typingMsg = {
					id: messageId++,
					content: '',
					isUser: false,
					isLoading: true,
					time: ''
				}
				this.messages.push(typingMsg)
				this.scrollToBottom()
				try {
					const res = await getInitChatInfo()

					// 移除加载状态
					this.messages = this.messages.filter(msg => msg.id !== typingMsg.id)

					if (res.code === 200) {
						const botMsg = {
							id: messageId++,
							content: res.content,
							isUser: false,
							time: this.getCurrentTime(),
							isLoading: false
						}
						this.messages.push(botMsg)
					} else {
						this.showError(`请求失败，状态码：${res.statusCode}`)
					}
				} catch (error) {
					this.messages = this.messages.filter(msg => msg.id !== typingMsg.id)
					this.showError('请求异常：' + error.errMsg)
				} finally {
					this.isSending = false
					this.scrollToBottom()
				}
			},
			// 新增文件操作方法
			toggleFilePanel() {
				this.showFilePanel = !this.showFilePanel
			},
			async chooseFile() {
				uni.chooseFile({
					count: 1,
					extension: ['jpg', 'png', 'pdf', 'docx'],
					success: (res) => {
						this.uploadFile(res.tempFiles[0])
					}
				})
			},
			uploadFile(file) {
				this.uploading = true
				this.error = ''

				try {

					// 执行上传
					const result = uploadFile({
						"filePath": file.path,
						"name": 'file',
					}).then(res => {
						if (res.code === 200) {
							this.filePath = res.data.path
							const botMsg = {
								id: messageId++,
								content: res.data.filename + ',上传成功!',
								isUser: false,
								time: this.getCurrentTime(),
								isLoading: false
							}
							this.messages.push(botMsg)
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
						this.showFilePanel = false
					})

				} catch (err) {
					this.error = err.message || '上传失败'
					uni.showToast({
						title: this.error,
						icon: 'none'
					})
				} finally {
					this.uploading = false
				}
			},
			async sendMessage() {
				if (!this.inputMessage.trim() || this.isSending) return

				// 添加用户消息
				const userMsg = {
					id: messageId++,
					content: this.inputMessage,
					isUser: true,
					time: this.getCurrentTime(),
					isLoading: false
				}
				this.messages.push(userMsg)

				// 添加加载状态消息
				const typingMsg = {
					id: messageId++,
					content: '',
					isUser: false,
					isLoading: true,
					time: ''
				}
				this.messages.push(typingMsg)
				this.scrollToBottom()

				// 准备请求参数
				const requestData = {
					query: this.inputMessage,
					filePath: this.filePath
				}

				this.inputMessage = ''
				this.isSending = true

				try {
					const res = await getChatInfo(requestData)

					// 移除加载状态
					this.messages = this.messages.filter(msg => msg.id !== typingMsg.id)

					if (res.code === 200) {
						const botMsg = {
							id: messageId++,
							content: res.content,
							isUser: false,
							time: this.getCurrentTime(),
							isLoading: false
						}
						this.messages.push(botMsg)
					} else {
						this.showError(`请求失败，状态码：${res.statusCode}`)
					}
				} catch (error) {
					this.messages = this.messages.filter(msg => msg.id !== typingMsg.id)
					this.showError('请求异常：' + error.errMsg)
				} finally {
					this.isSending = false
					this.scrollToBottom()
				}
			},

			calculateLayout() {
				const systemInfo = uni.getSystemInfoSync()
				// 计算底部安全区域
				this.safeAreaBottom = systemInfo.safeAreaInsets?.bottom || 0
				// 底部菜单高度适配（示例值，根据实际项目调整）
				this.bottomMenuHeight =  this.safeAreaBottom
				// 输入区域高度适配
				this.inputAreaHeight = 100 * (systemInfo.windowWidth / 375)
			},

			scrollToBottom() {
				this.$nextTick(() => {
					if (this.messages.length > 0) {
						const lastIndex = this.messages.length - 1
						this.lastMsgId = `msg${lastIndex}`
					}
				})
			},

			getCurrentTime() {
				const now = new Date()
				return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
			},

			showError(msg) {
				uni.showToast({
					title: msg,
					icon: 'none',
					duration: 3000
				})
			},
			// 处理HTML内容（安全过滤）
			processContent(html) {
				// // 安全过滤
				// const safeText = xss(html, {
				// 	whiteList: {
				// 		a: ['href', 'title', 'target'],
				// 		p: [],
				// 		span: ['style'],
				// 		code: [],
				// 		pre: [],
				// 		img: ['src', 'alt', 'style'],
				// 		b: [],
				// 		strong: [],
				// 		em: [],
				// 		ul: [],
				// 		ol: [],
				// 		li: [],
				// 		br: [],
				// 		table: [],
				// 		tr: [],
				// 		th: [],
				// 		td: []
				// 	},
				// 	css: {
				// 		whiteList: {
				// 			color: true,
				// 			'font-size': true,
				// 			'background-color': true
				// 		}
				// 	}
				// })
				// // 替换逻辑
				return html
					// 处理普通换行
					.replace(/([^\n])\n([^\n])/g, '$1<br/>$2')
					// 处理连续换行（转换为段落间距）
					.replace(/\n+/g, '</p><p>')
					// 包裹段落
					.replace(/^(.*)$/gm, '<p>$1</p>');
				
			},
			// 链接点击处理
			handleLinkClick(e) {
				console.log("e",e)
				uni.navigateTo({
				  url:'/pages/oa/leaveapply/index'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.chat-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
		box-sizing: border-box;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.chat-list {
		flex: 1;
		padding: 20rpx 20rpx 120rpx;
		overflow: auto;
	}

	// 新增样式部分
	.add-btn {
		padding: 12rpx;
		margin-right: 16rpx;
		background-color: #f8f8f8;
		border-radius: 8rpx;
	}

	.file-panel {
		position: absolute;
		bottom: 100%;
		left: 0;
		right: 0;
		background: #fff;
		padding: 30rpx;
		box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
		border-radius: 16rpx 16rpx 0 0;
		display: flex;
		justify-content: space-around;

		.file-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx;

			.file-text {
				font-size: 24rpx;
				color: #666;
				margin-top: 12rpx;
			}
		}
	}

	/* 消息附件展示 */
	.message-attachments {
		margin-top: 16rpx;
		display: flex;
		flex-wrap: wrap;
		gap: 12rpx;

		.attachment-item {
			background: #f8f8f8;
			border-radius: 8rpx;
			padding: 12rpx 20rpx;
			display: flex;
			align-items: center;

			.file-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 12rpx;
			}

			.file-info {
				.file-name {
					font-size: 26rpx;
					color: #333;
					max-width: 200rpx;
					text-overflow: ellipsis;
				}

				.file-status {
					font-size: 22rpx;
					color: #999;
				}
			}
		}
	}

	.message-item {
		margin: 20rpx 0;
		display: flex;

		&.user-message {
			justify-content: flex-end;

			.message-bubble {
				background-color: #07c160;
				color: white;
			}
		}

		&.bot-message {
			justify-content: flex-start;

			.message-bubble {
				background-color: white;
				color: #333;
			}
		}
	}

	.message-bubble {
		max-width: 70%;
		padding: 20rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

		.message-content {
			font-size: 28rpx;
			line-height: 1.5;
		}

		.message-time {
			display: block;
			font-size: 24rpx;
			color: #666;
			margin-top: 10rpx;
			text-align: right;
		}
	}

	.fixed-input {
		position: fixed;
		left: 0;
		right: 0;
		z-index: 999;
		background: rgba(255, 255, 255, 0.95);
		display: flex;
		align-items: center;
		padding: 20rpx;
		border-top: 1rpx solid #eee;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);

		.input-box {
			flex: 1;
			margin-right: 20rpx;
		}

		.send-btn {
			width: 150rpx;
			height: 70rpx;
			line-height: 70rpx;
		}
	}

	.typing-bubble {
		background: #fff;
		padding: 20rpx 30rpx;
		border-radius: 24rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.typing-indicator {
		display: flex;
		align-items: center;
		height: 40rpx;

		.dot {
			width: 12rpx;
			height: 12rpx;
			margin: 0 6rpx;
			background: #666;
			border-radius: 50%;
			animation: typing 1.4s infinite ease-in-out;

			&:nth-child(2) {
				animation-delay: 0.2s;
			}

			&:nth-child(3) {
				animation-delay: 0.4s;
			}
		}
	}

	.typing-text {
		font-size: 28rpx;
		color: #666;
		margin-left: 20rpx;
	}

	@keyframes typing {

		0%,
		80%,
		100% {
			transform: translateY(0);
			opacity: 0.6;
		}

		40% {
			transform: translateY(-10rpx);
			opacity: 1;
		}
	}

	/* 全局样式 */
	.mp-html {
		p {
			margin: 8px 0;
			line-height: 1.6;

			/* 处理空段落 */
			&:empty {
				display: none;
			}
		}

		br {
			/* 处理多平台显示差异 */
			content: "";
			display: block;
			margin-bottom: 8px;
		}
	}
</style>